/**
 * 音乐与音效管理
 */

var UnitTools = require('UnitTools')

class AudioManager {

    /**
     * 获取音量与音效的大小
     *
     * @return {[type]} [description]
     */
    static getVolume () {
        let music = cc.sys.localStorage.getItem(AudioManager.musicKey)
        let sound = cc.sys.localStorage.getItem(AudioManager.soundKey)
        let result = {}

        result.music = UnitTools.isNullOrUndefined(music)
            ? 0.5 : parseFloat(music)
        result.sound = UnitTools.isNullOrUndefined(sound)
            ? 0.5 : parseFloat(sound)
        return result
    }

    /**
     * 设置音量和音效的大小
     *
     * @param {[type]} type   1-音乐 2-音效
     * @param {[type]} number [description]
     */
    static setVolume (type, number) {
        if (type === 1) {
            cc.sys.localStorage.setItem(AudioManager.musicKey, number)
            cc.audioEngine.setMusicVolume(number)
        } else {
            cc.sys.localStorage.setItem(AudioManager.soundKey, number)
            cc.audioEngine.setEffectsVolume(number)
        }
    }

    /**
     * 根据路径加载并播放声音
     *
     * @param  {[type]} path [description]
     * @param  {[type]} type [description]
     * @return {[type]}      [description]
     */
    static loadAndPlaySound(node, path, type) {
        let audioNode = node.addComponent(cc.AudioSource)
        cc.loader.loadRes(path, cc.AudioClip, (err, audioClip) => {
            if (!err) {
                let volume = 0.5
                if (type == 1) {
                    volume = AudioManager.getVolume().music
                } else {
                    volume = AudioManager.getVolume().sound
                }

                audioNode.clip = audioClip
                audioNode.volume = volume
                audioNode.play()
            } else {
                console.log('加载错误,err:', err)
            }
        })
    }

    /**
     * 播放背景音乐
     *
     * @return {[type]} [description]
     */
    static palyBackgroudMusic(bg) {
        cc.loader.loadRes('audio/'+bg, cc.AudioClip, function (err, clip) {
            var audioID = cc.audioEngine.playMusic(clip, true)
            var results = AudioManager.getVolume()
            cc.audioEngine.setMusicVolume(results.music)
        })
    }

    /**
     * 播放音效
     *
     * @param  {[type]} sd [description]
     * @return {[type]}    [description]
     */
    static playSound(sd) {
        cc.loader.loadRes('audio/'+sd, cc.AudioClip, function (err, clip) {
            var audioID = cc.audioEngine.playEffect(clip, false)
            var results = AudioManager.getVolume()
            cc.audioEngine.setEffectsVolume(results.sound)
        })
    }
}

AudioManager.musicKey = 'music_voulme'
AudioManager.soundKey = 'sound_voulme'

module.exports = AudioManager
